// src/screens/main/ChatScreen.tsx
import React, { useState, useRef, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  FlatList,
  KeyboardAvoidingView,
  Platform,
  ActivityIndicator,
  Modal,
  Alert,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import Icon from 'react-native-vector-icons/MaterialIcons';
import { useSelector } from 'react-redux';
import { RootState } from '../../store/store';
import ChatBubble from '../../components/ChatBubble';
import aiService from '../../services/aiService';
import { ChatMessage } from '../../types';
import Toast from 'react-native-toast-message';
import { useNavigation } from '@react-navigation/native';
import { RootStackParamList } from '../../navigation/types.ts'
import { StackNavigationProp } from '@react-navigation/stack';
type NavigationProp = StackNavigationProp<RootStackParamList>;

interface ChatScreenProps {
  route?: {
    params?: {
      conversationId?: string;
    };
  };
}

const ChatScreen: React.FC<ChatScreenProps> = ({ route }) => {
  const flatListRef = useRef<FlatList>(null);
  const { subscription } = useSelector((state: RootState) => state.subscription);
  const navigation = useNavigation<NavigationProp>();
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [inputText, setInputText] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [selectedModel, setSelectedModel] = useState('gpt-4o-mini');
  const [showModelPicker, setShowModelPicker] = useState(false);
  const [conversationId, setConversationId] = useState<string>('');

  useEffect(() => {
    // 检查是否有传入的conversationId
    const paramConversationId = route?.params?.conversationId;
    if (paramConversationId) {
      setConversationId(paramConversationId);
      // 加载特定对话的历史记录
      loadChatHistory(paramConversationId);
    } else {
      // 生成新的会话ID
      const newConversationId = `conv_${Date.now()}`;
      setConversationId(newConversationId);
    }
  }, [route?.params?.conversationId]);

  const loadChatHistory = async (convId?: string) => {
    try {
      const targetConversationId = convId || conversationId;
      if (targetConversationId) {
        const history = await aiService.getChatHistory(targetConversationId);
        setMessages(history.messages);

        // 滚动到底部
        setTimeout(() => {
          flatListRef.current?.scrollToEnd({ animated: true });
        }, 100);
      }
    } catch (error) {
      console.error('Load history error:', error);
    }
  };

  const sendMessage = async () => {
    if (!inputText.trim()) return;

    const userMessage: ChatMessage = {
      id: Date.now().toString(),
      role: 'user',
      content: inputText,
      timestamp: new Date(),
    };

    setMessages(prev => [...prev, userMessage]);
    setInputText('');
    setIsLoading(true);

    try {
      const response = await aiService.chat({
        message: inputText,
        model: selectedModel,
        conversationId,
      });

      const aiMessage: ChatMessage = {
        id: (Date.now() + 1).toString(),
        role: 'assistant',
        content: response.reply,
        timestamp: new Date(),
        tokensUsed: response.usage.tokens,
      };

      setMessages(prev => [...prev, aiMessage]);

      // 滚动到底部
      setTimeout(() => {
        flatListRef.current?.scrollToEnd({ animated: true });
      }, 100);
    } catch (error: any) {
      Toast.show({
        type: 'error',
        text1: '发送失败',
        text2: error.message || '请检查网络连接',
      });
    } finally {
      setIsLoading(false);
    }
  };

  const clearChat = () => {
    Alert.alert(
      '清空对话',
      '确定要清空当前对话吗？',
      [
        { text: '取消', style: 'cancel' },
        {
          text: '确定',
          style: 'destructive',
          onPress: () => {
            setMessages([]);
            setConversationId(`conv_${Date.now()}`);
          }
        },
      ]
    );
  };

  const selectModel = (model: string) => {
    if (model === 'gpt-4' && subscription?.plan !== 'PREMIUM') {
      Alert.alert(
        '需要高级版',
        'GPT-4 模型仅限高级版用户使用',
        [
          { text: '取消', style: 'cancel' },
          { text: '升级套餐', onPress: () => navigation.navigate('Subscription') },
        ]
      );
      return;
    }
    setSelectedModel(model);
    setShowModelPicker(false);
  };

  const renderMessage = ({ item, index }: { item: ChatMessage; index: number }) => (
      <ChatBubble key={`${item.id}_${index}`} message={item} />
  );

  const renderEmptyState = () => (
    <View style={styles.emptyState}>
      <Icon name="chat" size={80} color="#ddd" />
      <Text style={styles.emptyStateTitle}>开始对话</Text>
      <Text style={styles.emptyStateText}>
        输入您的问题，AI助手会为您解答
      </Text>

      <View style={styles.suggestions}>
        <Text style={styles.suggestionsTitle}>试试这些问题：</Text>
        {[
          '今天的天气怎么样？',
          '给我推荐一些好看的电影',
          '如何学习编程？',
          '写一首关于春天的诗',
        ].map((suggestion, index) => (
          <TouchableOpacity
            key={index}
            style={styles.suggestionChip}
            onPress={() => setInputText(suggestion)}
          >
            <Text style={styles.suggestionText}>{suggestion}</Text>
          </TouchableOpacity>
        ))}
      </View>
    </View>
  );

  return (
    <SafeAreaView style={styles.container}>
      {/* Header */}
      <View style={styles.header}>
        <View style={styles.headerLeft}>
          <Text style={styles.headerTitle}>AI助手</Text>
          <TouchableOpacity
            style={styles.modelSelector}
            onPress={() => setShowModelPicker(true)}
          >
            <Text style={styles.modelText}>
              {selectedModel === 'gpt-4' ? 'GPT-4' : 'GPT-3.5'}
            </Text>
            <Icon name="arrow-drop-down" size={20} color="#667eea" />
          </TouchableOpacity>
        </View>

        <View style={styles.headerRight}>
          <TouchableOpacity style={styles.headerButton} onPress={clearChat}>
            <Icon name="clear-all" size={24} color="#666" />
          </TouchableOpacity>
          <TouchableOpacity style={styles.headerButton}>
            <Icon name="more-vert" size={24} color="#666" />
          </TouchableOpacity>
        </View>
      </View>

      {/* Messages List */}
      <FlatList
        ref={flatListRef}
        data={messages}
        renderItem={renderMessage}
        keyExtractor={item => item.id}
        contentContainerStyle={styles.messagesList}
        ListEmptyComponent={renderEmptyState}
        onContentSizeChange={() => messages.length > 0 && flatListRef.current?.scrollToEnd()}
      />

      {/* Loading Indicator */}
      {isLoading && (
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="small" color="#667eea" />
          <Text style={styles.loadingText}>AI正在思考...</Text>
        </View>
      )}

      {/* Input Area */}
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        keyboardVerticalOffset={90}
      >
        <View style={styles.inputContainer}>
          <View style={styles.inputWrapper}>
            <TextInput
              style={styles.input}
              placeholder="输入消息..."
              placeholderTextColor="#999"
              value={inputText}
              onChangeText={setInputText}
              multiline
              onSubmitEditing={sendMessage}
              returnKeyType="send"
            />
            <TouchableOpacity style={styles.attachButton}>
              <Icon name="attach-file" size={24} color="#999" />
            </TouchableOpacity>
          </View>
          <TouchableOpacity
            style={[styles.sendButton, !inputText.trim() && styles.sendButtonDisabled]}
            onPress={sendMessage}
            disabled={!inputText.trim() || isLoading}
          >
            <Icon name="send" size={24} color="#fff" />
          </TouchableOpacity>
        </View>
      </KeyboardAvoidingView>

      {/* Model Picker Modal */}
      <Modal
        visible={showModelPicker}
        transparent
        animationType="slide"
        onRequestClose={() => setShowModelPicker(false)}
      >
        <TouchableOpacity
          style={styles.modalOverlay}
          activeOpacity={1}
          onPress={() => setShowModelPicker(false)}
        >
          <View style={styles.modalContent}>
            <Text style={styles.modalTitle}>选择模型</Text>

            <TouchableOpacity
              style={[styles.modelOption, selectedModel === 'gpt-3.5-turbo' && styles.modelOptionSelected]}
              onPress={() => selectModel('gpt-3.5-turbo')}
            >
              <View>
                <Text style={styles.modelOptionTitle}>GPT-3.5</Text>
                <Text style={styles.modelOptionDesc}>快速响应，适合日常对话</Text>
              </View>
              {selectedModel === 'gpt-3.5-turbo' && (
                <Icon name="check-circle" size={24} color="#667eea" />
              )}
            </TouchableOpacity>

            <TouchableOpacity
              style={[styles.modelOption, selectedModel === 'gpt-4' && styles.modelOptionSelected]}
              onPress={() => selectModel('gpt-4')}
            >
              <View style={styles.modelOptionContent}>
                <View>
                  <Text style={styles.modelOptionTitle}>
                    GPT-4
                    {subscription?.plan !== 'PREMIUM' && (
                      <Text style={styles.premiumBadge}> 高级版</Text>
                    )}
                  </Text>
                  <Text style={styles.modelOptionDesc}>更强大的能力，更准确的回答</Text>
                </View>
                {subscription?.plan !== 'PREMIUM' && (
                  <Icon name="lock" size={20} color="#999" />
                )}
              </View>
              {selectedModel === 'gpt-4' && (
                <Icon name="check-circle" size={24} color="#667eea" />
              )}
            </TouchableOpacity>
          </View>
        </TouchableOpacity>
      </Modal>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f8f9fa', // 使用更柔和的背景色
  },
  // Header 样式
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 15,
    paddingVertical: 12, // 微调垂直内边距
    backgroundColor: '#fff',
    borderBottomWidth: 1,
    borderBottomColor: '#e9ecef', // 使用更浅的边框色
  },
  headerLeft: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  headerTitle: {
    fontSize: 20, // 稍大一点的标题
    fontWeight: 'bold',
    color: '#212529', // 深灰色，更易读
    marginRight: 8,
  },
  modelSelector: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 18, // 圆角更圆润
    backgroundColor: '#e7e7ff', // 浅紫色背景
  },
  modelText: {
    fontSize: 14,
    color: '#667eea',
    fontWeight: '600',
    marginRight: 2,
  },
  headerRight: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  headerButton: {
    padding: 8, // 增加点击区域
    marginLeft: 8,
  },
  // 消息列表
  messagesList: {
    flexGrow: 1,
    paddingHorizontal: 10,
    paddingVertical: 15,
  },
  // 空状态
  emptyState: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 40,
    paddingBottom: 50, // 向上移动一点
  },
  emptyStateTitle: {
    fontSize: 22,
    fontWeight: 'bold',
    color: '#343a40',
    marginTop: 20,
    marginBottom: 8,
  },
  emptyStateText: {
    fontSize: 15,
    color: '#6c757d', // 柔和的文本颜色
    textAlign: 'center',
    lineHeight: 22,
  },
  suggestions: {
    marginTop: 40,
    width: '100%',
  },
  suggestionsTitle: {
    fontSize: 14,
    color: '#adb5bd', // 更浅的灰色
    marginBottom: 15,
    textAlign: 'center',
  },
  suggestionChip: {
    backgroundColor: '#fff',
    paddingHorizontal: 18,
    paddingVertical: 12,
    borderRadius: 25,
    marginBottom: 12,
    borderWidth: 1,
    borderColor: '#dee2e6',
    shadowColor: '#000', // 添加轻微阴影
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.05,
    shadowRadius: 2,
    elevation: 2,
  },
  suggestionText: {
    fontSize: 14,
    color: '#495057',
    textAlign: 'center',
  },
  // 加载指示器
  loadingContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    padding: 8,
    backgroundColor: 'rgba(248, 249, 250, 0.8)', // 半透明背景
  },
  loadingText: {
    marginLeft: 10,
    fontSize: 14,
    color: '#667eea',
  },
  // 输入区域
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'flex-end', // 对齐底部，方便多行输入
    paddingHorizontal: 10,
    paddingVertical: 8,
    backgroundColor: '#fff',
    borderTopWidth: 1,
    borderTopColor: '#e9ecef',
  },
  inputWrapper: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#f1f3f5', // 输入框背景
    borderRadius: 25,
    paddingHorizontal: 15,
    marginRight: 10,
  },
  input: {
    flex: 1,
    paddingTop: 12, // 适配多行
    paddingBottom: 12,
    paddingRight: 10,
    fontSize: 16,
    color: '#333',
    maxHeight: 120, // 限制最大高度
  },
  attachButton: {
    padding: 5,
  },
  sendButton: {
    width: 48,
    height: 48,
    borderRadius: 24,
    backgroundColor: '#667eea',
    justifyContent: 'center',
    alignItems: 'center',
    shadowColor: '#667eea', // 添加阴影
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.4,
    shadowRadius: 3,
    elevation: 4,
  },
  sendButtonDisabled: {
    backgroundColor: '#b0b8f5', // 禁用的颜色
    shadowOpacity: 0.2,
    elevation: 0,
  },
  // 模型选择 Modal 样式
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    justifyContent: 'flex-end',
  },
  modalContent: {
    backgroundColor: '#fff',
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
    padding: 20,
    paddingBottom: 30, // 给底部更多空间
  },
  modalTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333',
    textAlign: 'center',
    marginBottom: 20,
  },
  modelOption: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 15,
    borderRadius: 12,
    borderWidth: 1.5,
    borderColor: '#e0e0e0',
    marginBottom: 12,
  },
  modelOptionSelected: {
    borderColor: '#667eea', // 选中状态边框
    backgroundColor: '#f0f0ff', // 选中状态背景
  },
  modelOptionContent: {
    flexDirection: 'row',
    alignItems: 'center',
    flex: 1,
    justifyContent: 'space-between',
  },
  modelOptionTitle: {
    fontSize: 16,
    fontWeight: '600',
    color: '#333',
  },
  modelOptionDesc: {
    fontSize: 13,
    color: '#666',
    marginTop: 4,
  },
  premiumBadge: {
    color: '#e67e22', // 高级版徽章颜色
    fontSize: 12,
    fontWeight: 'bold',
  },
});

export default ChatScreen;